<?php 
//all the class/function includes are managed in the includer file
include("include/includer.php");

$playlistDirectory = "../playlists";//removemelater

//get the configuration variables
getConfigVars();

//Get all the URL parameters (_GET)
if(isset($_GET['action'])) {
  $action = $_GET['action'];
}
if(isset($_GET['mode'])){
    $mode = $_GET['mode'];
}
if(isset($_GET['step'])){
    $step = $_GET['step'];
}
if(isset($_GET['playlistName'])){
    $playlistName = $_GET['playlistName'];
}
if(isset($_GET['playlistItem'])){
    $playlistItem = $_GET['playlistItem'];
}
if(isset($_GET['command'])){
    $command = $_GET['command'];
}

/**********************************************************************\
 *           Setup the core variables                                 *
 * path:            The path (not including the final folder)         *
 *                  ex: /share                                        *
 * file:            the specific file to be played/viewed/downloaded  *
 *                  ex: file.txt                                      *
 * folder:          the folder - this is for historical purposes      *
 *                  ex: folder                                        *
 * fullpath:        the full path including the final folder (no file)*
 *                  ex: /share/folder                                 *
 * fullpathToFile:  full path to the file                             *
 *                  ex: /share/folder/file.txt                        *
 * dirlist:         list of files in the fullpath                     *
\**********************************************************************/
//get the path
if(isset($_GET['path'])){
    if($_GET['path'] !=""){
      $path = $_GET['path'];
    }
    else $path = $config_filemandefaultpath;
}
else {
    $path = $config_filemandefaultpath;
}

//get the folder and file
if(isset($_GET['file'])){
    $file = $_GET['file'];
}
if(isset($_GET['folder'])){
    $folder = $_GET['folder'];
}

if(isset($folder)){
    //The folder is set -- creating the full path...
    $fullpath = $path."/".$folder;
    if(isset($file)){
        $fullpathToFile = $fullpath."/".$file;
    }
}
else{
    //The folder isn't set, so we'll make the full path the same as the path...
    $fullpath = $path;
    if(isset($file)){
        $fullpathToFile = $fullpath."/".$file;
    }
}
    
//setup the file extensions before running the loop
$audioext = array("mp3","wma","aac","aif","flac","iff","m4a","m4b","m4r","mid","midi","mod","mpa","ogg","ptf","ra","ram","rmj","sib","snd","wav");
$videoext = array("mkv","wmv","avi","3g2","3gp","asf","asx","divx","dvr-ms","f4v","fbr","flv","m4v","mov","mp4","mpeg","mpg","mts","ogm","qt","rcproject","rm","rmvb","smil","srt","stx","swf","ts","vob","vro","xvid");
$photoext = array("xcf","tif","thm","tga","tex","svgz","svg","stl","shp","sdb","qxp","qxd","psp","psd","ps","ppm","png","pln","pdf","pct","obj","mng","mb","max","ma","jpx","jpg","jpeg","inx","indd","hdp","gif","fxg","fpf","exif","eps","emz","emf","dxf","dwg","drw","dng","dgn","cr2","cpt","cdr","br5","bmp","blend","art","ai","abm","3dmf","3dm");
$basicext = array("nfo","txt","wps","wpd","sig","rtf","pages","opml","msg","lst","log","lit","docx","doc");
$configext = array("themepack","reg","rdf","psf","prx","properties","prf","ini","icc","cfg","conf");

//function for endKey
function endKey($array){
 end($array);
 return key($array);
}
        
//function for getting the items in the playlist and returning them in a JSON format
if($action == "getJSONplaylist"){
    session_start();
    $notLast = true;
    echo "[";
    //loop through the php session playlist and output it in the JSON format
    foreach($_SESSION['playlist'] as $key => $item){
        preg_match("/([^\`]+)\/([^\/]+)\.([^\/]+)$/",$item,$matches);
        //get the filename
        $filename = $matches[2].".".$matches[3];
        //get the directory
        $directory = $matches[1];
        //get the name from the file (without the extension)
        $name = $matches[2];
        //setup the URL to stream the file
        $fileURL = "fileman.php?path=".urlencode($directory)."&file=".urlencode($filename)."&action=stream";
        //output the format the jplayer likes
        echo "{name:\"$name\",mp3:\"$fileURL\"}";
        //if this is not the last file, add a comma to the end
        if(endKey($_SESSION['playlist']) == $key){ $notLast = false; }
        if($notLast){ echo ",\r\n"; }
    }
    echo "]";
    exit();
}
elseif($action == "ajaxDeletePlaylistItem"){
    //delete the request item and return true if possible
    unset($_SESSION['playlist'][$playlistItem]);
    $itemName = $_SESSION['playlist'][$playlistItem];
    //output true if it's not set
    if(!isset($_SESSION['playlist'][$playlistItem])){ echo "[{deleted:true}]"; } else { echo "[{deleted:false,phpitemName:".$itemName.",phpitemID:".$playlistItem."}]" ;}
    //then re-index the playlist
    $_SESSION['playlist'] = array_values($_SESSION['playlist']);
    exit();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<HEAD>
    <?php standardHead("Playlist Manager"); ?>
    <script type="text/javascript">
      window.onkeyup = function (event) {
        if (event.keyCode == 27) {
          window.close ();
        }
      }
      var refreshOnClose = false;

      window.onbeforeunload = confirmExit;
      function confirmExit()
      {
          if(refreshOnClose)
          window.opener.location.reload();
      }
    </script>
</HEAD>
<BODY style='background-color:white;padding:5px;'>
<div>
<?php
switch ($action) {
    case "save":
        if($_SESSION['playlist'] == null){
            echo "<div class='warningmessage'>You must have files added to the temporary playlist before you can use this function.</div>";
            echo "<div style='position:absolute;bottom:10px;right:10px;'><a href='' onClick='return self.close()'>Close This Window</a></div>";
        }else{
            if($step == null){
                if(isset($_SESSION['playlistLoaded'])){
                    echo "Are you sure you want to save over the existing playlist?";
                    echo "<div class='small'><strong>Playlist:</strong> ".$_SESSION['playlistLoaded'];
                    //check if the file exists
                    if(file_exists($playlistDirectory."/".$_SESSION['playlistLoaded'])){
                        echo "<br /><strong>Last Saved:</strong> ".date("M d Y g:i:s a", filemtime($playlistDirectory."/".$_SESSION['playlistLoaded']));
                    }
                    ?>
                    <div style='text-align:center'>
                    <form style="display:inline-block;">
                      <input type="hidden" name="action" value="new" />
                      <input type="hidden" name="step" value="playlistName" />
                      <input type="submit" value="Yes" />
                    </form>
                    <form style="display:inline-block;">
                      <input type="submit" value="No" onClick="return self.close()"/>
                    </form>
                    </div>
                <?php
                }else{
                      echo "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."?action=new";
                      //redirect the user to the save as option
                      header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."?action=new");
                }
            }
        }
        ?>
        <?php
        break;
    case "new":
        if($step == "deprecated"){
            if($_SESSION['playlist'] == null){
                echo "<div class='warningmessage'>You must have files added to the temporary playlist before you can use this function.</div>";
                echo "<div style='position:absolute;bottom:10px;right:10px;'><a href='' onClick='return self.close()'>Close This Window</a></div>";
            }else{
                echo "Would you like to create a new playlist?";
                ?>
                <div style='text-align:center'>
                <form style="display:inline-block;">
                  <input type="hidden" name="action" value="new" />
                  <input type="hidden" name="step" value="playlistName" />
                  <input type="submit" value="Yes" />
                </form>
                <form style="display:inline-block;">
                  <input type="submit" value="No" onClick="return self.close()"/>
                </form>
                </div>
                <br />
                <?php
                echo "<div class='infomessage'>Note: The items in your current playlist will be added to the new playlist.</div>";
            }
        }
        elseif($step == "playlistName" || $step == null){
            if($_SESSION['playlist'] == null){
                echo "<div class='warningmessage'>You must have files added to the temporary playlist before you can use this function.</div>";
                echo "<div style='position:absolute;bottom:10px;right:10px;'><a href='' onClick='return self.close()'>Close This Window</a></div>";
            }else{?>
            What do you want to call the playlist?
            <form>
              <input type='textbox' name='playlistName' />
              <input type="hidden" name="action" value="new" />
              <input type="hidden" name="step" value="playlistCreate" />
              <input type='submit' value='Create' />
            </form>
            <br /><br />
            <div class='infomessage'>Note: If you use the same name as an existing playlist, you will overwrite that playlist.</div>
            <?php }
        }elseif($step == "playlistCreate"){
            //clean the junk from the name
            $playlistName = trim($playlistName);
            $RemoveChars = array("([^a-zA-Z0-9-])", "(-{2,})" );
            $ReplaceWith = array("", "-");
            $playlistName = preg_replace($RemoveChars, $ReplaceWith, $playlistName);

            //check to see if the playlist already exists - if so confirm with the user they want to replace it
            if(file_exists($playlistDirectory."/".$playlistName.".playlist") && $mode != "confirmOverwrite"){
                echo "<div class='infomessage'>It looks like the playlist <strong>$playlistName</strong> already exists.</div> Do you want to overwrite the existing file?";
                ?>
                <div style='text-align:center'>
                <form style="display:inline-block;">
                  <input type="hidden" name="action" value="new" />
                  <input type="hidden" name="step" value="playlistCreate" />
                  <input type="hidden" name="mode" value="confirmOverwrite" />
                  <input type="hidden" name="playlistName" value="<?php echo $playlistName; ?>" />
                  <input type="submit" value="Yes" />
                </form>
                <form style="display:inline-block;">
                  <input type="hidden" name="action" value="new" />
                  <input type="hidden" name="step" value="playlistName" />
                  <input type="hidden" name="playlistName" value="<?php echo $playlistName; ?>" />
                  <input type="submit" value="No" />
                </form>
                </div>
                <?php
            }else{
                //create the playlist
                $playlistContent = implode("|",$_SESSION['playlist']);
                if(file_put_contents($playlistDirectory."/".$playlistName.".playlist", $playlistContent)){
                    //display a confirmation message
                    echo "<div class='infomessage'>The playlist <strong>$playlistName</strong> has been created.</div>";
                    echo "<br /><br /><div class='infomessage'>The media player will automatically be refreshed when this window is closed. <a href=\"javascript:void(0);\" onClick=\"refreshOnClose=false;return self.close();\">Click here</a> to close this window without refreshing the media player.</div>";
                    echo "<script>refreshOnClose = true;</script>";
                    //set the playlistLoaded session variable
                    $_SESSION['playlistLoaded'] = $playlistName.".playlist";
                }else{
                    //display a warning message
                    echo "<div class='warningmessage'>The playlist <strong>$playlistName</strong> could not be created in the folder:<br /> $playlistDirectory.</div>";
                }
                echo "<div style='position:absolute;bottom:10px;right:10px;'><a href='' onClick='return self.close()'>Close This Window</a></div>";
            }
        }
        break;
    case "delete":
        if($step == null){
            echo "Which playlist would you like to delete?";
            $dirlist = scandir($playlistDirectory);
            if($dirlist != null && count($dirlist) > 2){
            echo "<form>";
            echo "<input type='hidden' name='action' value='delete' />";
            echo "<input type='hidden' name='step' value='confirmDeletion' />";
            echo "<select name='playlistName'>";
                foreach($dirlist as $item){
                    //make sure it's a playlist file
                    $ext = strtolower(pathinfo($item, PATHINFO_EXTENSION));
                    if($ext == "playlist"){
                      //come up with a clean display name
                      $trimmedItem = str_replace(".".$ext,"",$item);
                      //echo it out as an option
                      echo "<option value='$item'>$trimmedItem</option>";
                    }
                }
            echo "<input type='submit' value='Delete' />";
            echo "</form>";
            }else{
              echo "<div class='warningmessage'>No Playlists Available</div>";
              echo "<div style='position:absolute;bottom:10px;right:10px;'><a href='' onClick='return self.close()'>Close This Window</a></div>";
            }
            echo "<br /><br />Alternatively, you can clear the current playlist: <br />";
            echo "<div style='text-align:center;'><form>";
            echo "<input type='hidden' name='action' value='delete' />";
            echo "<input type='hidden' name='step' value='clearPlaylist' />";
            echo "<input type='submit' value='Clear Playlist' />";
            echo "</form></div>";
        }
        elseif($step == "confirmDeletion"){
            echo "Are you sure you want to <font color='red'>delete</font> the playlist <strong>$playlistName</strong>?<br/>";
            ?>
                <div style='text-align:center;'>
                <form style="display:inline-block;">
                  <input type="hidden" name="action" value="delete" />
                  <input type="hidden" name="step" value="deletePlaylist" />
                  <input type="hidden" name="playlistName" value="<?php echo $playlistName; ?>" />
                  <input type="submit" value="Yes" />
                </form>
                <form style="display:inline-block;">
                  <input type="submit" value="No" onClick="return self.close()"/>
                </form>
                </div>
                <br /><br />
                <div class='warningmessage'>Once you delete the playlist, this cannot be undone.</div>
                <?php
            
        }
        elseif($step == "deletePlaylist"){
            //try to delete the playlist
            if(unlink($playlistDirectory."/".$playlistName)){
                echo "<div class='infomessage'>Successfully deleted the playlist $playlistName</div>";
            }else{
                echo "<div class='warningmesage'>Could not delete the playlist $playlistName</div>";
            }
            echo "<div style='position:absolute;bottom:10px;right:10px;'><a href='' onClick='return self.close()'>Close This Window</a></div>";
        }
        elseif($step == "clearPlaylist"){
            //clear the playlist session array
            unset($_SESSION['playlist']);
            //clear the loaded playlist name
            unset($_SESSION['playlistLoaded']);
            //then re-index it so the numbering makes sense
            $_SESSION['playlist'] = array_values($_SESSION['playlist']);
            //Let the user know what we did
            echo "<div class='infomessage'>The current playlist has been cleared.</div>";
            echo "<br /><br /><div class='infomessage'>The media player will automatically be refreshed when this window is closed. <a href=\"javascript:void(0);\" onClick=\"refreshOnClose=false;return self.close();\">Click here</a> to close this window without refreshing the media player.</div>";
            echo "<script>refreshOnClose = true;</script>";
            echo "<div style='position:absolute;bottom:10px;right:10px;'><a href='' onClick='return self.close()'>Close This Window</a></div>";
        }
        break;
    case "open":
        if($step == null){
        echo "Which playlist would you like to open? <br />";
        $dirlist = scandir($playlistDirectory);
        if($dirlist != null && count($dirlist) > 2){
        echo "<form>";
        echo "<input type='hidden' name='action' value='open' />";
        echo "<input type='hidden' name='step' value='confirmOpen' />";
        echo "<select name='playlistName'>";
            foreach($dirlist as $item){
                //make sure it's a playlist file
                $ext = strtolower(pathinfo($item, PATHINFO_EXTENSION));
                if($ext == "playlist"){
                  //come up with a clean display name
                  $trimmedItem = str_replace(".".$ext,"",$item);
                  //echo it out as an option
                  echo "<option value='$item'>$trimmedItem</option>";
                }
            }
        echo "<input type='submit' value='Open' />";
        echo "</form>";
        echo "<br /><br /><div class='infomessage'>The next page will give you options on how to open the playlist</div>";
        }else{
          echo "<div class='warningmessage'>No Playlists Available</div>";
          echo "<div style='position:absolute;bottom:10px;right:10px;'><a href='' onClick='return self.close()'>Close This Window</a></div>";
        }
        }
        elseif($step == "confirmOpen"){
            //Ask the user if they want to append it to the current playlist or clear what's already open and start fresh
            echo "You have two options for opening the saved playlist. You can either: <ol> <li>Add the songs to the currently loaded playlist </li><li>Discard the currently loaded playlist and open the selected playlist.</li> </ol>";
             ?><div style='text-align:center;'>
            <form style="display:inline-block;">
              <input type="hidden" name="action" value="open" />
              <input type="hidden" name="step" value="openPlaylist" />
              <input type="hidden" name="playlistName" value="<?php echo $playlistName; ?>" />
              <input type="hidden" name="mode" value="append" />
              <input type="submit" value="Add to Playlist"/>
            </form>
            <form style="display:inline-block;">
              <input type="hidden" name="action" value="open" />
              <input type="hidden" name="step" value="openPlaylist" />
              <input type="hidden" name="playlistName" value="<?php echo $playlistName; ?>" />
              <input type="hidden" name="mode" value="freshOpen" />
              <input type="submit" value="Discard and Open" />
            </form>
            </div>
            <?php
        }
        elseif($step == "openPlaylist"){
            //get the contents & split it out into an array.
            $playlistContents = explode("|",file_get_contents($playlistDirectory."/".$playlistName));
            switch($mode){
                case "append":
                    //Make sure the array is indexed properly
                    $_SESSION['playlist'] = array_values($_SESSION['playlist']);
                    //loop through the array appending it to the playlist session
                    foreach($playlistContents as $item){
                        $_SESSION['playlist'][] = $item;
                    }
                    echo "<div class='infomessage'>The items from <strong>$playlistName</strong> were added to the existing playlist. </div>";
                    echo "<br /><div class='infomessage'>The media player will automatically be refreshed when this window is closed. <a href=\"javascript:void(0);\" onClick=\"refreshOnClose=false;return self.close();\">Click here</a> to close this window without refreshing the media player.</div>";
                    echo "<script>refreshOnClose = true;</script>";
                    echo "<div style='position:absolute;bottom:10px;right:10px;'><a href='' onClick='return self.close()'>Close This Window</a></div>";
                    //set the session variable to the new playlist name
                    $_SESSION['playlistLoaded'] = $playlistName;
                    break;
                case "freshOpen":
                    //clear the playlist session array
                    unset($_SESSION['playlist']);
                    //then re-index it so the numbering makes sense
                    $_SESSION['playlist'] = array_values($_SESSION['playlist']);
                    //then loop through and add each of the new items
                    foreach($playlistContents as $item){
                        $_SESSION['playlist'][] = $item;
                    }
                    echo "<div class='infomessage'>The current playlist was discarded and the items from <strong>$playlistName</strong> were loaded.</div>";
                    echo "<br /><div class='infomessage'>The media player will automatically be refreshed when this window is closed. <a href=\"javascript:void(0);\" onClick=\"refreshOnClose=false;return self.close();\">Click here</a> to close this window without refreshing the media player.</div>";
                    echo "<script>refreshOnClose = true;</script>";
                    echo "<div style='position:absolute;bottom:10px;right:10px;'><a href='' onClick='return self.close()'>Close This Window</a></div>";
                    //set the session variable to the new playlist name
                    $_SESSION['playlistLoaded'] = $playlistName;
                    break;
                default:
                    echo "You have to select a method of opening the playlist";
            }
        }
        break;
    case "debug":
        //print_r($_SESSION['playlist']);
        echo "<ul>";
        echo "The end key is ".endKey($_SESSION['playlist']);
        foreach($_SESSION['playlist'] as $key => $item){
            echo "<li>[$key] $item</li>";
            preg_match("/([^\`]+)\/([^\/]+)\.([^\/]+)$/",$item,$matches);
            echo "<ul>";
            echo "<li>Full Match: ".$matches[0]."</li>";
            echo "<li>Path: ".$matches[1]."</li>";
            echo "<li>File: ".$matches[2]."</li>";
            echo "<li>Extension: ".$matches[3]."</li>";
            echo "<li>Future: ".$matches[4]."</li>";
            echo "</ul>";
        }
        echo "The end key is ".endKey($_SESSION['playlist']);
        echo "</ul>";
        break;
    case "addFolder":
        echo "<div class='infomessage'>Adding all MP3s from the folder $fullpath to the playlist...</div>";
        //scan the directory
        $dirlist = scandir($fullpath);
        foreach($dirlist as $item){
              //make sure it's a playlist file
              $ext = strtolower(pathinfo($item, PATHINFO_EXTENSION));
              //if it's an MP3, add it to the playlist
              //if($ext == "mp3"){
              if(in_array($ext,$audioext)){
                  $_SESSION['playlist'][] = $fullpath."/".$item;
              }
        }
        break;
    case "displayRemoteController":   
        displayController();          
        //if there's a command set, let's send it
        if($command != ""){
            sendCommand($command);
            echo "<div class='infomessage'>Command sent: $command</div>";
        }
        break;
    case "sendcommand":
        echo "<div class='warningmessage'>This action no longer exists. Use: action=displayRemoteController&command={command}. </div>";
        break;
    case "remoteplay":
          /***********************************************\
           *       Remote Play Calls (if selected)       *
          \***********************************************/
          // If selected, send the remote play commands (before generating the sidebar HTML
            switch($mode){
                case "playlist":
                    //session_start();
                    playFiles($_SESSION['playlist']);
                    echo "<div class='infomessage'>Remote play of the playlist you created should start on the popcornhour shortly...</div>";
                    break;
                case "folder":
                    if(isset($files)){
                        unset($files);
                    }
                    $dirlist = scandir($fullpath);
                    //$dirlist = scandir($fullpath);
                    foreach($dirlist as $file){
                        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                        //if it's an MP3, let's echo it out
                        if(in_array($ext,$audioext)){
                            //add the file to the files array
                            $files[] = $fullpath."/".$file;
                        }
                    }
                    playFiles($files);
                    echo "<div class='infomessage'>Remote play of the folder \"$fullpath\" should start on the popcornhour shortly...</div>";
                    //echo implode("<br />",$files); 
                    break;
            }
            break;
    default:
        echo "You must define an action";
}
?>
</div>
</BODY>